<template>
  <div class="ticket-board">
    <div class="board-columns">
      <div v-for="column in columns" :key="column.status" class="board-column">
        <div class="column-header">
          <div class="column-title">
            <component :is="column.icon" class="column-icon" />
            <span>{{ column.title }}</span>
            <a-badge :count="getColumnTickets(column.status).length" :number-style="{ backgroundColor: column.color }" />
          </div>
        </div>

        <div class="column-body">
          <draggable
            :list="getColumnTickets(column.status)"
            :group="{ name: 'tickets' }"
            item-key="id"
            class="ticket-list"
            @change="handleDragChange($event, column.status)"
          >
            <template #item="{ element }">
              <div class="ticket-card" @click="handleTicketClick(element)">
                <div class="ticket-header">
                  <a-tag :color="getPriorityColor(element.priority)">
                    {{ getPriorityLabel(element.priority) }}
                  </a-tag>
                  <span class="ticket-number">{{ element.ticketNumber }}</span>
                </div>

                <div class="ticket-title">{{ element.title }}</div>

                <div class="ticket-meta">
                  <div class="ticket-type">
                    <component :is="getTypeIcon(element.type)" style="font-size: 12px" />
                    <span>{{ getTypeLabel(element.type) }}</span>
                  </div>
                  <div class="ticket-time">
                    {{ formatTime(element.createdAt) }}
                  </div>
                </div>

                <div v-if="element.tags && element.tags.length > 0" class="ticket-tags">
                  <a-tag v-for="tag in element.tags.slice(0, 3)" :key="tag" size="small">
                    {{ tag }}
                  </a-tag>
                </div>

                <div class="ticket-footer">
                  <a-avatar-group :max-count="2" size="small">
                    <a-avatar v-if="element.assignedTo" size="small">
                      {{ element.assignedTo.charAt(0).toUpperCase() }}
                    </a-avatar>
                  </a-avatar-group>

                  <div class="ticket-indicators">
                    <a-tooltip v-if="element.sla?.isBreached" title="SLA Breached">
                      <ClockCircleOutlined style="color: #ff4d4f" />
                    </a-tooltip>
                    <a-tooltip v-if="element.comments && element.comments.length > 0" :title="`${element.comments.length} comments`">
                      <CommentOutlined />
                    </a-tooltip>
                  </div>
                </div>
              </div>
            </template>
          </draggable>

          <div v-if="getColumnTickets(column.status).length === 0" class="empty-column">
            <InboxOutlined style="font-size: 32px; color: #d9d9d9" />
            <div style="color: #999; margin-top: 8px">No tickets</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import draggable from 'vuedraggable'
import dayjs from 'dayjs'
import {
  InboxOutlined,
  FileTextOutlined,
  SyncOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  BugOutlined,
  BellOutlined,
  ToolOutlined,
  FileAddOutlined,
  CommentOutlined,
} from '@ant-design/icons-vue'
import { useTicketStore } from '@/stores/ticketStore'
import type { Ticket } from '@/api/ticket'
import { message } from 'ant-design-vue'

const router = useRouter()
const ticketStore = useTicketStore()

const columns = [
  { status: 'open', title: 'Open', icon: InboxOutlined, color: '#1890ff' },
  { status: 'in_progress', title: 'In Progress', icon: SyncOutlined, color: '#faad14' },
  { status: 'pending', title: 'Pending', icon: ClockCircleOutlined, color: '#fa8c16' },
  { status: 'resolved', title: 'Resolved', icon: CheckCircleOutlined, color: '#52c41a' },
  { status: 'closed', title: 'Closed', icon: CloseCircleOutlined, color: '#8c8c8c' },
]

const getColumnTickets = (status: string) => {
  if (!ticketStore.tickets || !Array.isArray(ticketStore.tickets)) {
    return []
  }
  return ticketStore.tickets.filter((t) => t.status === status)
}

const handleDragChange = async (event: any, newStatus: string) => {
  if (event.added) {
    const ticket: Ticket = event.added.element
    try {
      await ticketStore.updateTicketStatus(ticket.id, newStatus as Ticket['status'], 'Status updated by drag')
      message.success('Ticket status updated')
    } catch (error) {
      message.error('Failed to update status')
      // Refresh list to restore
      ticketStore.fetchTickets()
    }
  }
}

const handleTicketClick = (ticket: Ticket) => {
  router.push(`/tickets/${ticket.id}`)
}

const getPriorityColor = (priority: string) => {
  const colors: Record<string, string> = {
    critical: 'red',
    high: 'orange',
    medium: 'blue',
    low: 'default',
  }
  return colors[priority] || 'default'
}

const getPriorityLabel = (priority: string) => {
  const labels: Record<string, string> = {
    critical: 'Critical',
    high: 'High',
    medium: 'Medium',
    low: 'Low',
  }
  return labels[priority] || priority
}

const getTypeIcon = (type: string) => {
  const icons: Record<string, any> = {
    incident: BugOutlined,
    alert: BellOutlined,
    maintenance: ToolOutlined,
    request: FileAddOutlined,
  }
  return icons[type] || FileTextOutlined
}

const getTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    incident: 'Incident',
    alert: 'Alert',
    maintenance: 'Maintenance',
    request: 'Request',
  }
  return labels[type] || type
}

const formatTime = (time: string) => {
  return dayjs(time).fromNow()
}

onMounted(() => {
  // Only fetch if tickets are empty
  if (ticketStore.tickets.length === 0) {
    ticketStore.fetchTickets()
  }
})
</script>

<style scoped lang="scss">
.ticket-board {
  height: 100%;
  overflow-x: auto;
  padding: 16px;
}

.board-columns {
  display: flex;
  gap: 16px;
  min-width: fit-content;
}

.board-column {
  flex: 1;
  min-width: 320px;
  max-width: 360px;
  background: #f5f5f5;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
}

.column-header {
  padding: 12px 16px;
  background: white;
  border-radius: 8px 8px 0 0;
  border-bottom: 1px solid #f0f0f0;
}

.column-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  font-size: 14px;

  .column-icon {
    font-size: 16px;
  }
}

.column-body {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.ticket-list {
  min-height: 100px;
}

.ticket-card {
  background: white;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #f0f0f0;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
}

.ticket-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.ticket-number {
  font-size: 12px;
  color: #999;
  font-family: 'Courier New', monospace;
}

.ticket-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.5;
}

.ticket-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.ticket-type {
  display: flex;
  align-items: center;
  gap: 4px;
}

.ticket-tags {
  margin-bottom: 8px;
}

.ticket-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.ticket-indicators {
  display: flex;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.empty-column {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
}

::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: #d9d9d9;
  border-radius: 3px;

  &:hover {
    background: #bfbfbf;
  }
}
</style>
